<?php

/**
 * ProductPanelController is the default controller for this application
 */
class ProductPanelController extends BrowseControllerBase {
	/*
	 * UserProductDataService Object
	 */
	private $userProductDataService;
	
	/*
	 * UserProductDescriptionDataService Object
	 */
	private $userProductDescriptionDataService;
	
	/*
	 * SystemCategoryDataService Object
	 */
	private $systemCatgoryDataService;
	
	/*
	 * UserTaxDataService Object
	 */
	private $userTaxDataService;
	
	/*
	 * UserManufacturerDataService Object
	 */
	private $userManufacturerDataService;
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		
		$this->requireUserLogin ();
		
		/*
		 //Check if User is logged in
		 $authentication = new Authentication();
		 if ($authentication->getCurrentUserId() == null) {
			// Go on to login page
			$url = Zend_Registry::get('config')->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect($url);
			return -1;
			}
			*/
		
		$currentUserId = $this->authentication->getCurrentUserId ();
		
		//Check if Blogging Module is enabled
		if ($this->currentPackageOption) {
			$module = MODULE_ECOMMERCE;
			$isEnabled = $this->currentPackageOption->isEnabled ( $module );
			if ($isEnabled == false) {
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Index/errorAuthor';
				CommonUtils::redirect ( $url );
				return - 1;
			}
		}
		
		// Init all DataService
		$this->userProductDataService = new UserProductDataService ();
		
		$this->userProductDescriptionDataService = new UserProductDescriptionDataService ();
		
		$this->userTaxDataService = new UserTaxDataService ();
		
		$this->userManufacturerDataService = new UserManufacturerDataService ();
		
		$this->systemCatgoryDataService = new SystemCategoryDataService ();
		
		$this->loadAllPayment ( $currentUserId );
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 *
	 */
	
	public function indexAction() {
		$authentication = new Authentication ();
		
		$arrElement = array ();
		$arrElement ['ownerId'] = $authentication->getCurrentUserId ();
		
		$numRecordPerPage = 15;
		
		// Pager
		$start = $this->getQuery ( 'start', 0 );
		if ($start == '' || $start < 0) {
			$start = 0;
		}
		$totals = $this->userProductDataService->getTotals ( $arrElement );
		$itemList = $this->userProductDataService->getItems ( $arrElement, NULL, $start, $numRecordPerPage );
		if ($start > $totals) {
			$start = 0;
		}
		$link = Zend_Registry::get ( 'config' )->APPLICATION_URL . "/Browse/ProductPanel/Index";
		$pageLink = '';
		if ($totals > $numRecordPerPage) {
			$pageUtils = new PagerUtils ( $start, $totals, $numRecordPerPage, 10, $link );
			$pageLink = $pageUtils->writePagesLinks ( 0, 'start' );
			$pageLink .= "<br><span class=\"paing_text_nolink\">" . $pageUtils->writePagesCounter () . "</span>";
		}
		
		$this->smarty->assign ( 'pageLink', $pageLink );
		$this->smarty->assign ( 'itemList', $itemList );
		$this->smarty->assign ( 'itemCount', count ( $itemList ) );
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/ProductPanel/list_product.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	public function createAction() {
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		// Get list category of Photo
		$authentication = new Authentication ();
		$isError = false;
		$error = array ();
		$errorIndex = 0;
		
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			
			// get content
			$description = $this->getPost ( 'description', "" );
			
			// remove magic quotes
			if (get_magic_quotes_gpc ()) {
				$description = stripslashes ( $description );
			}
			$description = trim ( $description );
			
			// head title
			$headTitle = $this->getPost ( 'headTitle', "" );
			
			// Get description field
			$metaDescription = $this->getPost ( 'metaDescription', "" );
			
			// keywords
			$metaKeywords = $this->getPost ( 'metaKeywords', "" );
			
			// Main Title
			$name = $this->getPost ( 'name', "" );
			$categoryId = $this->getPost ( 'categoryId', "" );
			$manufacturerId = $this->getPost ( 'manufacturerId', "" );
			$taxId = $this->getPost ( 'taxId', "" );
			
			$price = $this->getPost ( 'price', "" );
			if (! is_numeric ( $price )) {
				$error [$errorIndex] = " Price is not number !";
				$errorIndex ++;
				$isError = true;
			}
			
			$quantity = $this->getPost ( 'quantity', "" );
			if (! is_numeric ( $quantity )) {
				$error [$errorIndex] = " Quantity is not number !";
				$errorIndex ++;
				$isError = true;
			}
			
			$weight = $this->getPost ( 'weight', "" );
			if (! is_numeric ( $weight )) {
				$error [$errorIndex] = " Weight is not number !";
				$errorIndex ++;
				$isError = true;
			}
			
			$model = $this->getPost ( 'model', "" );
			
			// Upload picture
			$picture = '';
			try {
				$picture = CommonUtils::uploadPictureEx ( 'picture' );
			} catch ( Exception $ex ) {
				
				//echo $ex->getMessage();
				

				// Ignore this case
				$resultMessage = 'Upload Picture fail.';
			}
			
			// check
			

			if (! empty ( $name ) && intval ( $price ) > 0 && $taxId != "" && $categoryId != "" && $manufacturerId != "" && $isError == false) {
				
				try {
					// Save data into database
					$productEntity = $this->userProductDataService->beforeCreate ();
					$productEntity->categoryId = $categoryId;
					$productEntity->taxId = $taxId;
					$productEntity->manufacturerId = $manufacturerId;
					$productEntity->picture = $picture;
					$productEntity->ownerId = $authentication->getCurrentUserId ();
					$productEntity->quantity = intval ( $quantity );
					$productEntity->weight = $weight;
					$productEntity->metaTitle = $headTitle;
					$productEntity->metaDescription = $metaDescription;
					$productEntity->metaKeywords = $metaKeywords;
					$productEntity->price = floatval ( $price );
					$productEntity->model = $model;
					$productEntity->status = 1;
					$productEntity->order = 0;
					$productEntity->sku = 0;
					$productEntity->updateSku ();
					$productId = $this->userProductDataService->create ( $productEntity );
					
					$productDescriptionEntity = $this->userProductDescriptionDataService->beforeCreate ();
					$productDescriptionEntity->id = $productId;
					$productDescriptionEntity->name = $name;
					$productDescriptionEntity->description = $description;
					$productDescriptionEntity->viewed = 0;
					$this->userProductDescriptionDataService->create ( $productDescriptionEntity );
					
					//echo $this->checkout_enable;
					//die();
					

					//Create Normal Product on 2Checkout
					if ($this->checkout_enable == "1") {
						$params = array ();
						$params ['name'] = $name;
						$params ['price'] = floatval ( $price );
						$params ['description'] = $description;
						$params ['vendor_product_id'] = $productEntity->sku;
						$config = $this->settingsDataService->get2CheckoutSettings ( $this->authentication->getCurrentUserId () );
						$checkoutGateway = new TwoCheckoutGateway ( $config );
						$checkoutGateway->setConfig ( $config );
						$ret = $checkoutGateway->createProduct ( $params, false );
					}
					
					// Redirect to edit page
					$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/ProductPanel/index';
					CommonUtils::redirect ( $url );
					exit ();
				} catch ( Exception $ex ) {
					$isError = true;
					// Ignore to process this case. Only show a message
					$error [$errorIndex] = 'The item cannot create successfully. Error Code = ' . $ex->getCode ();
					$errorIndex ++;
				}
			} else {
				$isError = true;
				$error [$errorIndex] = 'Please fill in all required fields';
				$errorIndex ++;
			}
		}
		
		$userId = $authentication->getCurrentUserId ();
		$categoryList = $this->systemCatgoryDataService->getByUserAndType ( $userId, CATEGORY_PRODUCT );
		$arrElement = array ();
		$arrElement ["ownerId"] = $userId;
		$taxList = $this->userTaxDataService->getItems ( $arrElement );
		$manufacturerList = $this->userManufacturerDataService->getItems ( $arrElement );
		$this->smarty->assign ( 'error', $error );
		$this->smarty->assign ( 'categoryList', $categoryList );
		$this->smarty->assign ( 'countCatList', count ( $categoryList ) );
		$this->smarty->assign ( 'taxList', $taxList );
		$this->smarty->assign ( 'countTaxList', count ( $taxList ) );
		$this->smarty->assign ( 'manufacturerList', $manufacturerList );
		$this->smarty->assign ( 'countManuList', count ( $manufacturerList ) );
		$this->smarty->assign ( 'manufacturerList', $manufacturerList );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/ProductPanel/create_product.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	public function editAction() {
		$authentication = new Authentication ();
		
		$isError = false;
		$error = array ();
		$errorIndex = 0;
		
		// Get id of page
		$id = $this->getPost ( 'id' );
		if (empty ( $id )) {
			$id = $this->getQuery ( 'id' );
		}
		// If the id of page does not exist, go on to view list page
		if (empty ( $id ) || ! is_numeric ( $id )) {
			$this->indexAction ();
			return false;
		}
		
		$id = intval ( $id );
		
		// Get data
		$productEntity = $this->userProductDataService->getById ( $id );
		$productDescriptionEntity = $this->userProductDescriptionDataService->getById ( $id );
		
		// check data
		if (empty ( $productEntity ) || empty ( $productDescriptionEntity )) {
			$this->indexAction ();
			return false;
		}
		
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		// submit
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			// get content
			$description = $this->getPost ( 'description', "" );
			
			// remove magic quotes
			if (get_magic_quotes_gpc ()) {
				$description = stripslashes ( $description );
			}
			$description = trim ( $description );
			
			// Main Title
			$name = $this->getPost ( 'name', "" );
			$categoryId = $this->getPost ( 'categoryId', "" );
			$manufacturerId = $this->getPost ( 'manufacturerId', "" );
			$taxId = $this->getPost ( 'taxId', "" );
			
			// head title
			$headTitle = $this->getPost ( 'headTitle', "" );
			// Get description field
			$metaDescription = $this->getPost ( 'metaDescription', "" );
			// keywords
			$metaKeywords = $this->getPost ( 'metaKeywords', "" );
			
			$price = $this->getPost ( 'price', "" );
			if (! is_numeric ( $price )) {
				$error [$errorIndex] = " Price is not number !";
				$errorIndex ++;
				$isError = true;
			}
			
			$quantity = $this->getPost ( 'quantity', "" );
			if (! is_numeric ( $quantity )) {
				$error [$errorIndex] = " Quantity is not number !";
				$errorIndex ++;
				$isError = true;
			}
			$weight = $this->getPost ( 'weight', "" );
			if (! is_numeric ( $weight )) {
				$error [$errorIndex] = " Weight is not number !";
				$errorIndex ++;
				$isError = true;
			}
			$model = $this->getPost ( 'model', "" );
			
			// Upload picture
			$picture = '';
			try {
				$picture = CommonUtils::uploadPictureEx ( 'picture' );
			} catch ( Exception $ex ) {
				
				//echo $ex->getMessage();
				

				// Ignore this case
				$resultMessage = 'Upload Picture fail.';
			}
			
			$productDescriptionEntity->description = $description;
			$productDescriptionEntity->name = $name;
			$productEntity->categoryId = $categoryId;
			$productEntity->taxId = $taxId;
			$productEntity->manufacturerId = $manufacturerId;
			$productEntity->price = $price;
			$productEntity->model = $model;
			$productEntity->metaTitle = $headTitle;
			$productEntity->metaDescription = $metaDescription;
			$productEntity->metaKeywords = $metaKeywords;
			$productEntity->quantity = $quantity;
			$productEntity->weight = $weight;
			if (! empty ( $picture )) {
				$productEntity->picture = $picture;
			}
			
			// check
			

			if (! empty ( $name ) && $taxId != "" && $categoryId != "" && $manufacturerId != "" && $isError == false) {
				
				try {
					$res = $this->userProductDataService->update ( $productEntity );
					$res = $this->userProductDescriptionDataService->update ( $productDescriptionEntity );
					
					//echo $this->checkout_enable;
					//die();
					

					//Update Data on 2Checkout
					if ($this->checkout_enable == "1") {
						
						$config = $this->settingsDataService->get2CheckoutSettings ( $this->authentication->getCurrentUserId () );
						$checkoutGateway = new TwoCheckoutGateway ( $config );
						$checkoutGateway->setConfig ( $config );
						
						$params = array ();
						$params ['name'] = $name;
						$params ['price'] = floatval ( $price );
						$params ['description'] = $description;
						if ($productEntity->sku == 0) {
							$productEntity->updateSku ();
						}
						$params ['vendor_product_id'] = $productEntity->sku;
						
						// get ProductDetails
						try {
							$info = $checkoutGateway->detailVendorProduct ( $productEntity->sku );
						} catch ( Exception $e ) {
							$info = false;
						}
						// Create
						if (! $info) {
							$checkoutGateway->createProduct ( $params, false );
						} // Edit
						else {
							$checkoutGateway->editProduct ( $package->sku, $params );
						}
					}
				} catch ( Exception $ex ) {
					$error [$errorIndex] = 'The item cannot create successfully. Error Code = ' . $ex->getCode ();
					$errorIndex ++;
					$isError = true;
				}
			} else {
				$isError = true;
				
				$error [$errorIndex] = 'Please fill in all required fields';
				$errorIndex ++;
			}
		}
		
		$this->smarty->assign ( 'error', $error );
		$this->smarty->assign ( 'id', $productEntity->id );
		$this->smarty->assign ( 'name', $productDescriptionEntity->name );
		$this->smarty->assign ( 'description', $productDescriptionEntity->description );
		
		$this->smarty->assign ( 'categoryId', $productEntity->categoryId );
		$this->smarty->assign ( 'taxId', $productEntity->taxId );
		$this->smarty->assign ( 'manufacturerId', $productEntity->manufacturerId );
		$this->smarty->assign ( 'picture', $productEntity->picture );
		$this->smarty->assign ( 'price', $productEntity->price );
		$this->smarty->assign ( 'quantity', $productEntity->quantity );
		$this->smarty->assign ( 'weight', $productEntity->weight );
		$this->smarty->assign ( 'headTitle', $productEntity->metaTitle );
		$this->smarty->assign ( 'metaDescription', $productEntity->metaDescription );
		$this->smarty->assign ( 'metaKeywords', $productEntity->metaKeywords );
		$this->smarty->assign ( 'model', $productEntity->model );
		$this->smarty->assign ( 'productEntity', $productEntity );
		$userId = $authentication->getCurrentUserId ();
		$categoryList = $this->systemCatgoryDataService->getByUserAndType ( $userId, CATEGORY_PRODUCT );
		$arrElement = array ();
		$arrElement ["ownerId"] = $userId;
		$taxList = $this->userTaxDataService->getItems ( $arrElement );
		$manufacturerList = $this->userManufacturerDataService->getItems ( $arrElement );
		
		$this->smarty->assign ( 'categoryList', $categoryList );
		$this->smarty->assign ( 'countCatList', count ( $categoryList ) );
		$this->smarty->assign ( 'taxList', $taxList );
		$this->smarty->assign ( 'countTaxList', count ( $taxList ) );
		$this->smarty->assign ( 'manufacturerList', $manufacturerList );
		$this->smarty->assign ( 'countManuList', count ( $manufacturerList ) );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/ProductPanel/edit_product.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	public function delAction() {
		// Get Id of page
		$id = $this->getQuery ( 'id', 0 );
		
		if (! empty ( $id ) && is_numeric ( $id ) && $this->isDemoMode == false) {
			
			$id = intval ( $id );
			// Delete page
			$res = $this->userProductDataService->del ( $id );
		}
		// Redirect to edit page
		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/ProductPanel/index';
		CommonUtils::redirect ( $url );
		return;
	}
}
